<template>
    <view class="content">
        <van-nav-bar :title="scrolling? navBarTitle : '' " left-arrow @click-left="onClickLeft"> </van-nav-bar>

        <scroll-view class="scroll-content" scroll-y :lower-threshold="80" @scroll="scrollPage"  show-scrollbar="false">

            <view class="tabTop">
                <view class="title"> 收银台</view>
            </view>
            <view class="moneyBg">
                <view class="text">待支付</view>
                <view class="money">￥{{payMoney}}</view>
            </view>
            <view style="margin:32px 24px 0px 24px;">
                <view class="content_title">支付金额</view>
                <view class="jifen_tips" v-if="showTips">如果没有积分，将自动兑换成金额支付</view>
                <view class="num">￥{{payMoney}}</view>
            </view>
            <view style="margin:32px 24px 0px 24px; padding-bottom: 85px;">
                <view class="content_title">支付方式</view>
                <view class="content_select">
                    <radio-group @change="radioChange">
                        <view class="payItem" v-for="(item, index) in paymentList" :key="index" :id="item.id">
                            <view class="payItemLeft">
                                <view class="icon"> <img :src="item.imgUrl" alt="" style="width: 22px; height: 17px;">
                                </view>
                                <view class="name">{{ item.name }} <span class="walletBalance" v-if="item.id===2">({{walletBalance}})</span> </view>
                            </view>
                            <radio color="#FF6203" :value="index" :checked="item.isChecked" icon-size="12px"/>
                        </view>                    
                    </radio-group>
                </view>
            </view>

        </scroll-view>
        <van-toast id="van-toast" />
        <view class="goodsAction bottom" >
            <!-- <van-goods-action>
                <van-goods-action-button color="#FF6203" text="立即支付" @click="onClickbutton" />
            </van-goods-action> -->
            <van-button type="primary" @click="onClickbutton" :disabled="isSubmitting" style="height: 86rpx;line-height: 86rpx;">{{ isSubmitting ? '支付中...' : '立即支付' }}</van-button>
            <!-- <van-button type="primary" @click="onClickbutton" style="height: 86rpx;line-height: 86rpx;">立即支付</van-button> -->

        </view>
    </view>
</template>

<script>
import { SOURCE_TYPE } from '@/utils/constant'
import Toast from '@/wxcomponents/vant/toast/toast'
import {createPrePaymentApi} from '@/api/shoppingCart'
import {getWxUserInfoApi} from '@/api/mine'
import {getOrderPaymentStatusApi} from '@/api/order'

export default {
    data() {
        return {
            navBarTitle: '收银台',
            scrolling: false,
            payMoney: '0',
            showTips: false,
            paymentList: [
                {
                    id: 1,
                    imgUrl: 'https://17lelife-bucket.oss-cn-beijing.aliyuncs.com/WeChat-App-Picture/WeChat1129.png',
                    name: '微信支付',
                    walletBalance: ''
                },
                {
                    id: 2,
                    imgUrl: 'https://17lelife-bucket.oss-cn-beijing.aliyuncs.com/WeChat-App-Picture/wallet1129.png',
                    name: '我的钱包',
                    walletBalance: ''
                }
            ],
            walletBalance: '0',
            productId:null,
            orderId: null,
            params: undefined, //接受从路由传过来的参数
            isSubmitting: false, // 新增提交状态标识
            payResultParams:null , //支付结果参数
            source: SOURCE_TYPE.DEFAULT, // 支付来源
        }
    },
    onLoad(data) {
        if (data && data.params) {
            this.params = JSON.parse(decodeURIComponent(data.params))
            if (this.params.pageSymbol === 'act') {
                this.showTips = true
            } else {
                this.showTips = false
            }
            if (this.params.totalAmount) {
                this.payMoney = this.params.totalAmount
                this.orderId = this.params.orderId
            }
            if (this.params.productId){
                this.productId = this.params.productId
            }
            this.source = this.params.source || undefined
            console.log('支付参数','原始页面来源', this.source)
        }
    },
    onReady() {
        this.paymentList.forEach(element => { //默认选中第一个  微信支付
            this.$set(element, 'isChecked', element.id === 1)
        })
        this.getWxUserInfo()
    },
    methods: {
        // 滑动
        scrollPage(e) {
            console.log(e.detail.scrollTop, this.scrolling)
            if (e.detail.scrollTop > 25 && !this.scrolling) {
                this.scrolling = true
            } else if ((e.detail.scrollTop <= 25 && this.scrolling) || (e.detail.scrollTop <= 25 && !this.scrolling)) {
                this.scrolling = false
            }
        },
        // 返回键
        onClickLeft() {
            const params = {
              source: this.source,
              orderId: this.orderId,
              payMoney: this.payMoney,
              status: 'unpaid',
              orderStatus:'4'
            }
            // 跳转至待付订单页面
            uni.redirectTo({
                url: '/pages/orders/orderDetails?params=' +
                encodeURIComponent(JSON.stringify(params))
            });
        },


        // 立即支付
        async onClickbutton() {
            if (this.isSubmitting) {
                return false
            }
            this.isSubmitting = true;  // 进入提交状态

            try {
                // 获取选中的支付方式
                const selectedPayment = this.paymentList.find(item => item.isChecked);
                // 校验支付方式
                if (!selectedPayment) {
                    Toast('请选择支付方式');
                    return;
                }
                // 判断选中的支付方式
                if (selectedPayment.id === 1) {
                    await this.createPrePayment_yeePay()  //易宝支付
                    // await this.createPrePayment_lsPay() //乐刷支付
                    // await this.createPrePayment_wxPay()  //微信支付
                } else if (selectedPayment.id === 2) {
                    if( Number(this.walletBalance) < Number(this.payMoney)) {
                        Toast('余额不足')
                        return
                    }
                    await this.createPrePayment_wallet()  //余额支付
                }
            } catch (error) {
                console.error('支付异常:', error);
            } finally {
                this.isSubmitting = false; // 无论成功失败都重置状态
            }
        },

        // 单选框
        radioChange(e) {
            console.log('radio发生change事件，携带value值为：', e.detail.value)

            this.paymentList.forEach((item, index) => {
                if (Number(index) === Number(e.detail.value)) {
                    item.isChecked = true
                } else {
                    item.isChecked = false
                }
            })
        },


        /**
         * 接口
         */

        //获取用户钱包余额
        async getWxUserInfo() {
            getWxUserInfoApi().then(res => {
                if (res.code === 200) {
                    this.walletBalance = res.data.walletBalance
                }
            })
        },
        // 创建预支付的接口 乐刷支付
        async createPrePayment_lsPay() {
            const params = {
                orderId: this.orderId,
                orderNo: this.params.orderNo,
                orderAmount: this.payMoney,
                // userId: "string",
                paymentMethod: "LS_PAY",  //ALIPAY(1, "支付宝"), WECHAT_PAY(2, "微信支付"),LS_PAY(4, "乐刷支付"), BANK_CARD(3, "银行卡"), WALLET(0, "钱包余额");
                // callbackUrl: undefined
            }
            this.isSubmitting =true // 进入提交状态
            try {
                const res = await createPrePaymentApi(params)

                if (res.code === 200) {
                    // 调用微信支付
                    const paymentData = JSON.parse(res.data.jspayInfo)
                    console.log(paymentData)
                    wx.requestPayment({
                        // provider: 'wxpay',
                        timeStamp: paymentData.timeStamp, //"时间戳字符串",  // 例如："1624008625"
                        nonceStr: paymentData.nonceStr, //"随机字符串",    // 例如："5K8264ILTKCH16CQ2502SI8ZNMTM67VS"
                        package: paymentData.package,
                        signType: paymentData.signType, //"RSA",          // 签名算法
                        paySign: paymentData.paySign, //"支付签名"
                        success: async  () => {
                            // 支付成功回调，实现自定义的业务逻辑
                            console.log('唤起支付组件成功：', res);
                            const checkResult = await this.getOrderPaymentStatus(this.orderId)
                            if (checkResult) {
                                Toast('支付成功');
                                this.payResultParams = {
                                    ...(this.payResultParams || {}),
                                    orderId: this.orderId,
                                    source: this.source
                                };
                                console.log('支付结果参数：', this.payResultParams);
                                this.pageChange(this.payResultParams);
                            } else {
                                Toast.fail('支付结果确认失败');
                                // uni.redirectTo({
                                //      url: `/pages/orders/orderDetails?status=unpaid&orderId=${this.orderId}&source=${this.source}`
                                // });
                                const signParams = {
                                    source: this.source,
                                    orderId: this.orderId,
                                    status: 'unpaid',
                                }
                                // 跳转至待付订单页面
                                uni.reLaunch({
                                    url: '/pages/orders/orderDetails?params=' +
                                        encodeURIComponent(JSON.stringify(signParams))
                                });
                            }
                        },
                        fail: (err) => {
                            Toast('支付取消或失败');
                            console.error('支付失败:', err);
                            if (err.errMsg == 'requestPayment:fail cancel' || err.errMsg.includes('cancel')) {
                                // 用户取消支付
                                wx.showToast({
                                    title: '支付已取消',
                                    icon: 'none'
                                });
                                const signParams = {
                                    source: this.source,
                                    orderId: this.orderId,
                                    status: 'unpaid',
                                }
                                // 跳转至待付订单页面
                                uni.reLaunch({
                                    url: '/pages/orders/orderDetails?params=' +
                                        encodeURIComponent(JSON.stringify(signParams))
                                });
                            } else {
                                // 其他支付错误
                                wx.showToast({
                                    title: '支付失败，请重试',
                                    icon: 'none'
                                });
                            }

                        }
                    });
                }else{
                    wx.showToast({
                        title: res.message || '创建支付订单失败，请重试',
                        icon: 'none',
                        duration: 2000
                    });
                }
            } catch (error) {
                Toast('支付请求失败');
                console.error('支付异常:', error);
            } finally {
                this.isSubmitting = false; // 无论成功失败都重置状态
            }
        },
        // 创建预支付的接口 乐刷支付
        async createPrePayment_yeePay() {
            const params = {
                orderId: this.orderId,
                orderNo: this.params.orderNo,
                orderAmount: this.payMoney,
                // userId: "string",
                paymentMethod: "YEE_PAY",  //ALIPAY(1, "支付宝"), WECHAT_PAY(2, "微信支付"),LS_PAY(4, "乐刷支付"), BANK_CARD(3, "银行卡"), WALLET(0, "钱包余额"); YEE_PAY易宝支付
                // callbackUrl: undefined
            }
            this.isSubmitting =true // 进入提交状态
            try {
                const res = await createPrePaymentApi(params)

                if (res.code === 200) {
                    // 调用微信支付
                    const paymentData = JSON.parse(res.data.payParams)
                    console.log(paymentData)
                    wx.requestPayment({
                        // provider: 'wxpay',
                        timeStamp: paymentData.timeStamp, //"时间戳字符串",  // 例如："1624008625"
                        nonceStr: paymentData.nonceStr, //"随机字符串",    // 例如："5K8264ILTKCH16CQ2502SI8ZNMTM67VS"
                        package: paymentData.package,
                        signType: paymentData.signType, //"RSA",          // 签名算法
                        paySign: paymentData.paySign, //"支付签名"
                        success: async  () => {
                            // 支付成功回调，实现自定义的业务逻辑
                            console.log('唤起支付组件成功：', res);
                            this.orderId = res.data.orderId
                            const checkResult = await this.getOrderPaymentStatus(this.orderId)
                            console.log('该订单支付结果：', checkResult)
                            if (checkResult) {
                                Toast('支付成功');
                                this.payResultParams = {
                                    ...(this.payResultParams || {}),
                                    orderId: this.orderId,
                                    source: this.source,
                                    payType:'wx'
                                }
                                console.log('支付结果参数：', this.payResultParams)
                                this.pageChange(this.payResultParams);
                            } else {
                                Toast.fail('支付结果确认失败');
                                // uni.redirectTo({
                                //      url: `/pages/orders/orderDetails?status=unpaid&orderId=${this.orderId}&source=${this.source}`
                                // });
                                const signParams = {
                                    source: this.source,
                                    orderId: this.orderId,
                                    status: 'unpaid',
                                }
                                // 跳转至待付订单页面
                                uni.reLaunch({
                                    url: '/pages/orders/orderDetails?params=' +
                                        encodeURIComponent(JSON.stringify(signParams))
                                });
                            }
                        },
                        fail: (err) => {
                            Toast('支付取消或失败');
                            console.error('支付失败:', err);
                            if (err.errMsg == 'requestPayment:fail cancel' || err.errMsg.includes('cancel')) {
                                // 用户取消支付
                                wx.showToast({
                                    title: '支付已取消',
                                    icon: 'none'
                                });
                                const signParams = {
                                    source: this.source,
                                    orderId: this.orderId,
                                    status: 'unpaid',
                                }
                                // 跳转至待付订单页面
                                uni.reLaunch({
                                    url: '/pages/orders/orderDetails?params=' +
                                        encodeURIComponent(JSON.stringify(signParams))
                                });
                            } else {
                                // 其他支付错误
                                wx.showToast({
                                    title: '支付失败，请重试',
                                    icon: 'none'
                                });
                            }

                        }
                    });
                }else{
                    wx.showToast({
                        title: res.message || '创建支付订单失败，请重试',
                        icon: 'none',
                        duration: 2000
                    });
                }
            } catch (error) {
                Toast('支付请求失败');
                console.error('支付异常:', error);
            } finally {
                this.isSubmitting = false; // 无论成功失败都重置状态
            }
        },
        // 创建预支付的接口 微信支付
        async createPrePayment_wxPay() {
            const params = {
                orderId: this.orderId,
                orderNo: this.params.orderNo,
                orderAmount: this.payMoney,
                // userId: "string",
                paymentMethod: "WECHAT_PAY",  //WECHAT_PAY    LS_PAY   //WXZF
                // callbackUrl: undefined
            }
            this.isSubmitting = true // 进入提交状态
            try {
                const res = await createPrePaymentApi(params)

                if (res.code === 200) {
                    // 添加类型检查和安全解析
                    let paymentData;
                    try {
                        // 检查是否是字符串
                        if (typeof res.data.payParams === 'string') {
                            paymentData = JSON.parse(res.data.payParams);
                        } else {
                            // 如果已经是对象则直接使用
                            paymentData = res.data.payParams;
                        }
                    } catch (e) {
                        console.error('支付参数解析失败:', res.data.payParams);
                        throw new Error('支付参数格式错误');
                    }

                    console.log('支付参数:', paymentData)
                    wx.requestPayment({
                        // provider: 'wxpay',
                        timeStamp: paymentData.timeStamp, //"时间戳字符串",  // 例如："1624008625"
                        nonceStr: paymentData.nonceStr, //"随机字符串",    // 例如："5K8264ILTKCH16CQ2502SI8ZNMTM67VS"
                        package: paymentData.package,
                        signType: paymentData.signType, //"RSA",          // 签名算法
                        paySign: paymentData.paySign, //"支付签名"
                        success: async  () => {
                            // 支付成功回调，实现自定义的业务逻辑
                            console.log('唤起支付组件成功：', res);
                            const checkResult = await this.getOrderPaymentStatus(this.orderId)
                            if (checkResult) {
                                Toast('支付成功')
                                this.payResultParams = {
                                    ...(this.payResultParams || {}),
                                    orderId: this.orderId,
                                    source: this.source,
                                    payType: 'wallet'
                                }
                                console.log('支付结果参数：', this.payResultParams)
                                this.pageChange(this.payResultParams)
                            } else {
                                Toast.fail('支付结果确认失败');
                                // uni.redirectTo({
                                //      url: `/pages/orders/orderDetails?status=unpaid&orderId=${this.orderId}&source=${this.source}`
                                // });
                                const signParams = {
                                    source: this.source,
                                    orderId: this.orderId,
                                    status: 'unpaid',
                                }
                                // 跳转至待付订单页面
                                uni.reLaunch({
                                    url: '/pages/orders/orderDetails?params=' +
                                        encodeURIComponent(JSON.stringify(signParams))
                                });
                            }
                        },
                        fail: (err) => {
                            Toast('支付取消或失败');
                            console.error('支付失败:', err);
                            if (err.errMsg == 'requestPayment:fail cancel' || err.errMsg.includes('cancel')) {
                                // 用户取消支付
                                wx.showToast({
                                    title: '支付已取消',
                                    icon: 'none'
                                });
                                const signParams = {
                                    source: this.source,
                                    orderId: this.orderId,
                                    status: 'unpaid',
                                }
                                // 跳转至待付订单页面
                                uni.reLaunch({
                                    url: '/pages/orders/orderDetails?params=' +
                                        encodeURIComponent(JSON.stringify(signParams))
                                });
                                // // 跳转至待付订单页面
                                // uni.redirectTo({
                                //      url: `/pages/orders/orderDetails?status=unpaid&orderId=${this.orderId}&source=${this.source}`
                                // });
                            } else {
                                // 其他支付错误
                                wx.showToast({
                                    title: '支付失败，请重试',
                                    icon: 'none'
                                });
                            }

                        }
                    });
                } else {
                    wx.showToast({
                        title: res.message || '创建支付订单失败，请重试',
                        icon: 'none',
                        duration: 2000
                    });
                }
            } catch (error) {
                Toast('支付请求失败');
                console.error('支付异常:', error);
            } finally {
                this.isSubmitting = false; // 无论成功失败都重置状态
            }
        },
        
        // 钱包余额支付
        async createPrePayment_wallet() {
            const params = {
                orderId: this.orderId,
                orderNo: this.params.orderNo,
                orderAmount: this.payMoney,
                paymentMethod: "WALLET",
            }
            this.isSubmitting =true // 进入提交状态
            try {
                const res = await createPrePaymentApi(params)

                if (res.code === 200) {
                    Toast('支付成功')
                    const checkResult = await this.getOrderPaymentStatus(this.orderId)
                    if (checkResult) {
                        Toast('支付成功')
                        this.payResultParams = {
                            ...(this.payResultParams || {}),
                            orderId: this.orderId,
                            source: this.source,
                            payType:'wallet'
                        }
                        console.log('支付结果参数：', this.payResultParams)
                        this.pageChange(this.payResultParams);
                    //    this.pageChange({orderId:res.data.thirdOrderId,source:this.source,payType:'wallet'})
                    }else {
                        Toast.fail('支付结果确认失败');
                        const signParams = {
                            source: this.source,
                            orderId: this.orderId,
                            status: 'unpaid',
                        }
                        // 跳转至待付订单页面
                        uni.reLaunch({
                            url: '/pages/orders/orderDetails?params=' +
                                encodeURIComponent(JSON.stringify(signParams))
                        });
                    }
                    //    this.pageChange(this.payResultParams);
                    // if (res.data && res.data.thirdOrderId) {
                    //     Toast.success('支付成功');
                    //     this.pageChange({ orderId: res.data.thirdOrderId });
                    // } else {
                    //     Toast.fail('支付成功但订单号异常');
                    //     console.error('接口返回数据异常:', res);
                    // }
                } else { // 处理非200的响应
                    Toast.fail(res.msg || '钱包支付失败');
                    console.error('接口返回错误:', res);
                }
            } catch (error) {
                // Toast('余额钱包支付请求失败');
                // 处理网络错误和异常
                const errMsg = error.errMsg || error.message;
                if (errMsg.includes("request:fail")) {
                    Toast.fail('网络请求失败，请检查网络');
                } else {
                    Toast.fail('支付请求异常');
                }
                console.error('支付异常:', error);
                // const signParams = {
                //     source: this.source,
                //     orderId: this.orderId,
                //     status: 'unpaid',
                // }
                // // 跳转至待付订单页面
                // uni.navigateTo({
                //     url: '/pages/orders/orderDetails?params=' +
                //         encodeURIComponent(JSON.stringify(signParams))
                // });
            } finally {
                this.isSubmitting = false; // 无论成功失败都重置状态
            }
        },

        // 查看订单支付状态
        async getOrderPaymentStatus(orderId) {
            try {
                // 最多查询5次，间隔1秒
                const maxRetries = 5;
                for (let i = 0; i < maxRetries; i++) {
                    const res = await getOrderPaymentStatusApi(orderId); // 假设已有查询接口
                    if (res.code !== 200) {
                        console.error('支付状态查询失败:', res.msg);
                        return false;
                    }
                    if(res.code === 200){
                        this.payResultParams = Object.assign(
                            {},
                            res.data || {},  // 防止res.data为undefined
                            { source: this.source }
                        );
                    }
                    if (res.data.status === 'SUCCESS') {
                        return true;
                    }
                    await new Promise(resolve => setTimeout(resolve, 1000));
                }
                return false;
            } catch (error) {
                console.error('支付状态查询失败:', error);
                return false;
            }
        },

        // 页面跳转
        pageChange(params){
            params.productId = this.productId
            // params.orderId = this.orderId
            console.log(params,'页面跳转参数',this.showTips,'showTips')
            if (this.showTips === false) {
                uni.reLaunch({ // 使用重定向跳转替换当前页（关键修改）
                    url: '/pages/payment/paySuccess?params=' +
                        encodeURIComponent(JSON.stringify(params))
                })
            } else { //报名成功
                uni.reLaunch({
                    url: '/pages/findPage/registResult?params=' +
                        encodeURIComponent(JSON.stringify(params))
                })
            }
        }


    }
}
</script>

<style scoped>
.content {
    background-color: #ffffff;
    display: flex;
    flex-direction:column;
    height:100vh;
    overflow:hidden;
    box-sizing: border-box;
}
.scroll-content {
    flex: 1;
    height: 1px;
}
.tabTop{
    padding-top:25px;
    padding-left: 24px;
    padding-right: 24px;
}
.title{
    font-size: 30px;
    text-align: left;
    color: #111111;
}
.moneyBg{
    margin-top: 19px;
    margin-left: 24px;
    margin-right: 24px;
    background: linear-gradient(to bottom, #FFDCC6,#FFF3EC);
    padding-left:33px ;
    padding-top: 45px;
    padding-bottom: 57px;
}
.text{
    font-size: 14px;
    text-align: left;
    color: #111111;
    line-height: 14px;
}
.money{
    font-size: 31px;
    color: #111111;
    text-align: left;
    line-height: 31px;
    margin-top:20px;
}

.content_title{
    font-size:20px;
    text-align: left;
    color: #111111;
    line-height: 20px;
}
.content_select{
    margin-top: 24px;
}
.jifen_tips{
    font-size: 22rpx;
    text-align: left;
    color: #666666;
    line-height: 22rpx;
    margin-top: 45rpx;
    margin-bottom: 45rpx;
}
.num{
    border: 1px solid #333333;
    font-size: 12px;
    text-align: center;
    color: #111111;
    line-height: 12px;
    padding: 10px 0px;
    margin-top: 24px;
    width: 96px;

}
.payItem{
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 27px;
}
.payItem:last-child{
    margin-bottom: 0px;
}

.payItemLeft{
    display: flex;
    align-items: center;
}
.name{
    font-size: 13px;
    color: #111111;
    line-height: 13px;
    margin-left: 11px;
}
.walletBalance{
    font-size: 11px;
    color: #666666;
    line-height: 11px;
    margin-left: 7px;
}

.btn-area{
    position: fixed;
    bottom: 0;
    width: calc(100% - 48px);
    /* height: 50px; */
    display: flex;
    background: transparent;
    z-index: 100;
}





::v-deep .van-nav-bar__left {
    width: 56px;
    height: 44px;
}

::v-deep .van-icon {
    color: #242629 !important;
}
::v-deep .van-cell{
    padding-left: 0px !important;
    border-bottom: 1px solid #f9f9f9;
}
::v-deep .van-button{
    background-color: #FF6203;
    width: 100%;
    border-radius: 38rpx;
    font-size:28rpx;
    text-align: center;
    color: #FFFFFF;
    height: 86rpx;
    line-height: 86rpx;
}
::v-deep .van-button--primary {
  width: 100%;
  height: 86rpx;
  border-radius: 38rpx;
  background: #ff6203;
}
</style>
